import re
from rest_framework import serializers
from .models import Area
from users.models import Address


class AreasSerializer(serializers.ModelSerializer):
    class Meta:
        model = Area
        fields = ('id', 'name')


# class AreaSerializser(serializers.ModelSerializer):
#     class Meta:
#         model = Area
#         fields = ('id','name')


class AddressesSerializer(serializers.ModelSerializer):
    province = serializers.StringRelatedField(read_only=True,label='省')
    city = serializers.StringRelatedField(read_only=True,label='市')
    district = serializers.StringRelatedField(read_only=True,label='区')
    city_id = serializers.IntegerField(write_only=True)
    province_id = serializers.IntegerField(write_only=True)
    district_id = serializers.IntegerField(write_only=True)

    class Meta:
        model = Address
        exclude = ('user','is_deleted','create_time','update_time')

    def validate(self, attrs):
        if not re.match(r'1[3-9]\d{9}', attrs['mobile']):
            raise serializers.ValidationError('手机格式不正确')
        return attrs

    def create(self, validated_data):
        user = self.context['request'].user
        validated_data['user'] = user

        address = super().create(validated_data)

        return address


class TitleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ('title',)






